<%@ page language="java" import="java.util.*"  import="java.util.regex.Matcher"
		 import="java.util.regex.Pattern,com.alibaba.fastjson.TypeReference" %>
<%@ page import="com.alibaba.fastjson.JSON" %>
<%!
	public final static String PATTERN = "<img src=\'http://[^>]*?>";

	// 获取图片的像素
	public static String pixel (String imgStr) {
		Pattern pattern =  Pattern.compile("width=\".*?\"");
		Matcher m = pattern.matcher(imgStr);
		String width = "";
		String height = "";
		while(m.find()) {
			width = m.group().split("width=\"")[1].split("\"")[0].trim();
		}
		pattern =  Pattern.compile("height=\".*?\"");
		m = pattern.matcher(imgStr);
		while(m.find()) {
			height = m.group().split("height=\"")[1].split("\"")[0].trim();
		}
		if ("".equals(width)) {
			return "";
		}
		return width + " * " + height;
	}

	public Map<String, String>  getImg(String content, String pattern) {
		Map<String, String>  resMap = new HashMap<String, String> ();
		ArrayList listImg = new ArrayList();
		Pattern p1 = Pattern.compile("<img[^>]*?>", Pattern.CASE_INSENSITIVE);
		Matcher m1 = p1.matcher(content);
		int j = 0;
		while (m1.find()) {
			String imgStr = m1.group();
			String pixel = pixel(imgStr);
			Matcher m3  = Pattern.compile("src\\s*=\\s*'?(.*?)('|>|\\s+)").matcher(imgStr);
			while(m3.find()){
				imgStr = m3.group(1) + "";
			}
			Map map = new HashMap();
			map.put("ref", "!--IMG#" + j + "--");
			map.put("src", imgStr);
			map.put("pixel", pixel);
			listImg.add(map);
			++j;
		}
		Pattern p = Pattern.compile("<img[^>]*?>",Pattern.CASE_INSENSITIVE);
		Matcher m = p.matcher(content);
		int i = 0;
		while (m.find()) {
			content =content.replaceFirst(m.group(), "!--IMG#" + i + "--");
			i++;
		}
		resMap.put("imgs", JSONUtil.toJson(listImg).replaceAll("\"", "\\\""));
		resMap.put("content", content);
		return resMap;
	}

	// 获取病人列表
	public Message patients(Input input) {
		Message msg = new Message();
		Integer pageNum = input.getInt("page", 1);; 		// 页码
		Integer itemCount = input.getInt("item_count", 2);  // 每一页条目
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		if (pageNum <= 0 || itemCount <= 0) {
			return new Message(30041, "参数不合法，请输入正确的页码或限值");
		}
		String date = input.getDesc("date", "");
		String keywords = input.getDesc("keywords", "");
		Where where = new Where("hospital=", hospital).and("status=", STATUS_ENABLE).and("type=", USER_PATIENT);
		if (!"".equals(date))
			where.and("concat(FROM_UNIXTIME(cTime/1000, '%Y-%m-%d'), '')=", date);
		if (!"".equals(keywords))
			where.and("(userName like '%" + keywords + "%' or name like '%" + keywords +"%')");
		List<Map> ranks = QBuilder.db("basedb").select("new map(id as id, name as name, userName as user_name,avatar as avatar, gender as gender,concat(FROM_UNIXTIME(cTime/1000, '%Y-%m-%d %H:%i:%s'), '') as create_time)").from("User").where(where).order("cTime", "desc").page(itemCount, pageNum).query().getResultObj();
		List<Long> rankCount = QBuilder.db("basedb").select("count(*)").from("User").where(where).order("cTime", "desc").query().getResultObj();
		List<Map> accountList = QBuilder.db("basedb").select("new map(uid as uid, count(uid) as famliy)").from("UserProfile").where(new Where("hospital=", hospital).and("status=", STATUS_ENABLE)).group("uid").query().getResultObj();
		for (Map map:ranks) {
			Integer id = (Integer)map.get("id");
			if (map.get("avatar") == null)
				map.put("avatar", USER_AVATAR_M);
			map.put("famliy", 0L);
			for (Map famliy:accountList) {
				Integer fid = (Integer)famliy.get("uid");
				if (fid.equals(id)) {
					map.put("famliy", famliy.get("famliy"));
				}
			}
		}
		Long size = rankCount.get(0);
		Map resultMap = new HashMap();
		resultMap.put("rank", ranks);
		resultMap.put("current_page", pageNum);
		resultMap.put("page_count",  size%itemCount == 0?(size/itemCount):(size/itemCount + 1));
		resultMap.put("count", size);
		msg.put("data", resultMap);
		return msg;
	}

	// 获取标签
	public Message labels(Input input) {
		Message msg = new Message();
		// category:3科室中新闻标签,1医院新闻标签，如果医院没有标签，则使用公共标签
		Integer category = input.getInt("category", 3);
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		List labelList = QBuilder.db("basedb").queryHql("from Label where hospital = " + hospital + " and category=" + category + " and status=" + STATUS_ENABLE + " order by id asc");
		if (labelList.size() == 0) {
			labelList = QBuilder.db("basedb").queryHql("from Label where hospital = " + 0 + " and category=" + category + " and status=" + STATUS_ENABLE +" order by id asc");
		}
		if (labelList.size() == 0){
			msg.setErrcode(30041);
			msg.setErrmsg("暂无可选标签");
		} else {
			msg.put("labels", labelList);
		}
		return msg;
	}
	//新闻列表
	Message newsList(Input input) {

		Map map = new HashMap();
		Integer pageNum = input.getInt("page", 1); // 页码
		Integer itemCount = input.getInt("item_count", 12); // 每一页条目
		Integer category = input.getInt("category", 0); //新闻分类
		Integer status = input.getInt("status", 1); //新闻分类
		String table = "News n";
		String order = "desc"; // 排序
		Integer hospital = input.getInt("hospital", -1); // 医院id
		String labelId = input.getDesc("labelId", "-1").replace(".0", ""); // 通过标签与新闻关联查询   不传默认通过category新闻类别查
		Where where = new Where("n.category=", category);

		if (pageNum <= 0 || itemCount <= 0) {
			return new Message(30041, "参数不合法，请输入正确的页码或限值");
		}
		String selectContent = "distinct new map(n.id as id , n.newsId as news_id, n.url as url, n.title as title, n.summary as summary, n.time as time, n.img as img, n.jsonString as json, n.category as category, n.author as author)" ;

		List<Map> newsList = QBuilder.db("basedb").select(selectContent).from("News as n").where(new Where("n.hospital=", hospital).and("n.category=", labelId).and("n.status = ", status)).page(itemCount, pageNum).order("n.newsId", order).query().getResultObj();
		List<Long> rankCount = QBuilder.db("basedb").queryHql("select count(*) from News where hospital=" + hospital + " and status=" + status+" and category="+labelId);
		if (order.equals("asc")) { // 上拉加载时倒序
			Collections.reverse(newsList);
		}

		Message msg = new Message(0);
		Map resultMap = new HashMap();
		Long size = rankCount.get(0);

		List<Integer> topList = QBuilder.db("basedb").select("n.id").from("Top as t, News as n").where(new Where("n.hospital=", hospital).and("t.oid=n.id").and("t.status=", STATUS_ENABLE).and("n.status=", STATUS_ENABLE).and("t.category=", 3).and("t.groupId=", 1)).query().getResultObj();
		for (Map rank:newsList) {
			rank.put("top", 0);
			Integer id = (Integer)rank.get("id");
			if (topList.contains(id))
				rank.put("top", 1);
		}

		resultMap.put("rank", newsList);
		resultMap.put("current_page", pageNum);
		resultMap.put("page_count",  size%itemCount == 0?(size/itemCount):(size/itemCount + 1));
		resultMap.put("count", size);
		msg.put("data", resultMap);
		return msg;
	}

	// 新闻列表
	Message newsList1(Input input) {

		Map map = new HashMap();
		Integer pageNum = input.getInt("page", 1);; // 页码
		Integer itemCount = input.getInt("item_count", 12); // 每一页条目
		if (pageNum <= 0 || itemCount <= 0) {
			return new Message(30041, "参数不合法，请输入正确的页码或限值");
		}
		Integer hospital = input.getInt("hospital", -1); // 医院id
		String labelId = input.getDesc("labelId", "-1").replace(".0", ""); // 通过标签与新闻关联查询   不传默认通过category新闻类别查
		String deptCode = input.getDesc("deptCode", "0");
		String order = "asc"; // 排序
		String newsId = "";
		String selectContent = "new map(n.id as id , n.newsId as news_id, n.url as url, n.title as title, n.summary as summary, n.time as time, n.img as img, n.jsonString as json, n.tag as tag, n.category as category, n.branchName as branch_name)";
		String table = "News n";
		Where where = new Where("n.category=", labelId);
		if (!deptCode.equals("0")) {
			where.and("n.branch=", "dept-" + deptCode);
		}
		List<Map> ranks = QBuilder.db("basedb").select("new map(n.id as id , n.newsId as news_id, n.url as url, n.title as title, n.summary as summary, n.time as time, n.img as img, n.jsonString as json, n.tag as tag, n.category as category, n.branchName as branch_name,n.author as author)").from(table).where(where.and("n.hospital=", hospital).and("n.status = ", STATUS_ENABLE)).order("n.newsId", order).page(itemCount, pageNum).query().getResultObj();
		List<Long> rankCount = QBuilder.db("basedb").select("count(*)").from(table).where(where.and("n.hospital=", hospital).and("n.status = ", STATUS_ENABLE)).order("n.newsId", order).query().getResultObj();

		if (ranks.size() == 0) {
			Message msg = new Message(30041, "暂无相关数据");
			return msg;
		}
		if (order.equals("asc")) { // 上拉加载时倒序
			Collections.reverse(ranks);
		}
		Message msg = new Message(0);
		Long size = rankCount.get(0);
		Map resultMap = new HashMap();
		List<Integer> topList = QBuilder.db("basedb").select("n.id").from("Top as t, News as n").where(new Where("n.hospital=", hospital).and("t.oid=n.id").and("t.status=", STATUS_ENABLE).and("n.status=", STATUS_ENABLE).and("t.category=", 3).and("t.groupId=", 1)).query().getResultObj();
		for (Map rank:ranks) {
			rank.put("top", 0);
			Integer id = (Integer)rank.get("id");
			if (topList.contains(id))
				rank.put("top", 1);
		}
		resultMap.put("rank", ranks);
		resultMap.put("current_page", pageNum);
		resultMap.put("page_count",  size%itemCount == 0?(size/itemCount):(size/itemCount + 1));
		resultMap.put("count", size);
		msg.put("data", resultMap);
		List<String> list = QBuilder.db("basedb").queryHql("select deptName from Dept where hospital="+hospital+" and deptId='"+deptCode+"' and status="+STATUS_ENABLE);
		System.out.println(list.size());
		if (list.size() != 0)
			msg.put("deptName", list.get(0));
		return msg;
	}

	//展示新闻详情
	public Message news(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String news_id = input.getDesc("news_id","39385").replace(".0","");
		List newsList = QBuilder.db("basedb").queryHql("from News where hospital="+hospital+" and status="+STATUS_ENABLE+" and id="+news_id);
		if(newsList.size() == 0)
			return new Message(30041, "没有这条新闻");
		else
			msg.put("data", newsList.get(0));
		return msg;
	}

	// 查看轮播新闻
	public Message tops(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String selectContent = "new map(n.id as id , n.newsId as news_id, n.url as url, n.title as title, n.summary as summary, n.time as time, n.img as img, n.jsonString as json, n.tag as tag, n.category as category, n.branchName as branch_name,t.id as tid,n.author as author,t.orderId as order_id)";
		List<Map> list = QBuilder.db("basedb").select(selectContent).from("Top as t, News as n").where(new Where("n.hospital=", hospital).and("t.oid=n.id").and("t.status=", STATUS_ENABLE).and("n.status=", STATUS_ENABLE).and("t.groupId=", 1)).order("t.orderId", "asc").query().getResultObj();
		for(int i=0;i<list.size();i++){
			Map map = list.get(i);
			List l = (List) JSON.parse(map.get("img").toString().replaceAll("\r","").replaceAll("\n",""));
			map.put("img",l);

		}
		msg.put("data", list);
		return msg;
	}


	// 设置轮播
	public Message setTop(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		Integer newsId = input.getInt("news_id", -1);
		List<Map> list = QBuilder.db("basedb").select("new map(n.id as id)").from("Top as t, News as n").where(new Where("n.hospital=", hospital).and("t.oid=n.id").and("t.status=", STATUS_ENABLE).and("n.status=", STATUS_ENABLE).and("t.groupId=", 1)).query().getResultObj();
		if (list.size() >= 5) {
			return new Message(30041, "轮播数量已经超过5个限制，请在首页轮播列表里移除一些再操作");
		}
		Top top = new Top();
		top.setHospital(hospital);
		top.setGroupId(1);
		top.setOid(newsId);
		top.setCategory(1);
		top.setOrderId(list.size() + 1);
		DBTools.db("basedb").addItem(top);
		return msg;
	}

	// 取消设置轮播
	public Message unsetTop(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		Integer newsId = input.getInt("news_id", -1);
		List<Top> selfList = QBuilder.db("basedb").select().from("Top").where(new Where("hospital=", hospital).and("groupId=", 1).and("status=", STATUS_ENABLE).and("oid=", newsId)).query().getResultObj();
		if (isEmpty(selfList))
			return new Message(30041, "没有这个新闻");
		Top self = selfList.get(0);
		self.setStatus(STATUS_DISABLE);
		DBTools.db("basedb").modItem(self, self.getId());
		List<Top> list = QBuilder.db("basedb").queryHql("from Top where groupId=1 and status=1 and hospital=" + hospital + " order by orderId asc");
		for (int i =0; i<list.size();i++) {
			Top top = list.get(i);
			QBuilder.db("basedb").execHQL("update Top set orderId=" + (i + 1) + " where id=" + top.getId()) ;
		}
		return msg;
	}

	// 添加新闻
	public Message addNews(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String deptCode = input.getDesc("deptCode","");
		String labelId = input.getDesc("labelId","").replace(".0","");
		String title = input.getDesc("title","");
		String author = input.getDesc("author","");
		String summary = input.getDesc("summary","");
		String content = input.getDesc("content","");
		Map<String, String> imgMap = getImg(content,  PATTERN);
		Map jsonMap = new HashMap();
		jsonMap.put("attachs", new ArrayList());
		//获取时间
		Calendar cal = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String time = sdf.format(cal.getTime());
		//新建新闻对象
		News news = new News();
		news.setTitle(title);
		news.setAuthor(author);
		news.setSummary(summary);
		news.setTime(time);
		news.setHospital(hospital);
		news.setCategory(Integer.valueOf(labelId));
		news.setBranch("dept-"+deptCode);
		news.setContent(Tools.getDesc(imgMap.get("content")));
		news.setImg(Tools.getDesc(imgMap.get("imgs")));
		List<Map> imgs = JSONUtil.fromJson(news.getImg(), new TypeReference<List<Map>>(){});
		news.setJson(jsonMap);
		if (imgs.size() != 0 ) {
			String url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
			news.setJson("news_thumbnail", url);
		}
		try {
			DBTools.db("basedb").addItem(news);
			news.setNewsId(news.getId());
			DBTools.db("basedb").modItem(news,news.getId());
		} catch (Exception e) {
			e.printStackTrace();
			msg.setErrcodeAndErrmsg(30041, "新闻添加失败");
		}
		return msg;
	}

	// 删除新闻
	public Message deleteNews(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String newsId = input.getDesc("news_id","").replace(".0","");
		QBuilder.db("basedb").execHQL("update News set status= " + STATUS_DISABLE + " where hospital=" + hospital + " and id=" + newsId);
		return msg;
	}

	// 修改新闻
	public Message updateNews(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String newsId = input.getDesc("news_id","").replace(".0","");
		String title = input.getDesc("title","");
		String author = input.getDesc("author","");
		String content = input.getDesc("content","");
		try {
			content = URLDecoder.decode(content, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		Map<String, String> imgMap = getImg(content,  PATTERN);
		Map jsonMap = new HashMap();
		jsonMap.put("attachs", new ArrayList());
		String summary = input.getDesc("summary","");
		List<News> list = QBuilder.db("basedb").queryHql("from News where hospital=" + hospital + " and id=" + newsId + " and status=" + STATUS_ENABLE);
		if(list.size() == 0){
			return new Message(30041, "没有这条新闻");
		} else {
			News news = list.get(0);
			news.setTitle(title);
			news.setAuthor(author);
			news.setSummary(summary);
			news.setContent(Tools.getDesc(imgMap.get("content")));
			news.setImg(Tools.getDesc(imgMap.get("imgs")));
			List<Map> imgs = JSONUtil.fromJson(news.getImg(), new TypeReference<List<Map>>(){});
			news.setJson(jsonMap);
			if (imgs.size() != 0 ) {
				String url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
				news.setJson("news_thumbnail", url);
			}
			try {
				DBTools.db("basedb").modItem(news,news.getId());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return msg;
	}

	// 轮播排序
	public Message topOrder(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String act = input.getDesc("mod");
		Integer id = input.getInt("tid", 0);
		Integer orderId = input.getInt("order_id", 0);
		List<Top> list = QBuilder.db("basedb").select().from("Top as t").where(new Where("t.id=", id).and("t.groupId=", 1).and("t.status=", STATUS_ENABLE).and("t.hospital=", hospital)).query().getResultObj();
		Top self = list.get(0);
		String ho = "t.orderId>" + orderId;
		String order = "asc";
		if ("up".equals(act)) {
			order = "desc";
			ho = "t.orderId<" + orderId;
		}
		list = QBuilder.db("basedb").select().from("Top as t").where(new Where("t.groupId=", 1).and("t.status=", STATUS_ENABLE).and(ho).and("t.hospital=", hospital)).order("t.orderId", order).query().getResultObj();
		if (list.size() == 0)
			return new Message(30041, "没有置顶新闻");
		Top top = list.get(0);
		self.setOrderId(top.getOrderId());
		top.setOrderId(orderId);
		QBuilder.db("basedb").execHQL("update Top set orderId=" + top.getOrderId() + " where id=" + top.getId());
		QBuilder.db("basedb").execHQL("update Top set orderId=" + self.getOrderId() + " where id=" + self.getId());
		return msg;
	}

	// 添加科室，一级科室和二级科室共用一个接口
	public Message addDept(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String deptName = input.getDesc("deptName", "");
		String deptCode = input.getDesc("deptCode", "");
		String address = input.getDesc("address", "");
		String phone = input.getDesc("phone", "");
		String content = input.getDesc("content", "");
		String branch = input.getDesc("branch", "1");
		String branchName = input.getDesc("branch_name", "本部");
		Map<String, String> imgMap = getImg(content, PATTERN);
		Map jsonMap = new HashMap();
		jsonMap.put("attachs", new ArrayList());
		String img = input.getDesc("head_image", "");
		String dType = input.getDesc("type", "1"); // 1一级科室 2二级科室
		List<Dept> codeList = QBuilder.db("basedb").queryHql("from Dept where hospital=" + hospital + " and deptId='" + deptCode + "' and status=" + STATUS_ENABLE);
		if(codeList.size() > 0){
			return new Message(30031, "科室id已存在");
		}
		//创建对象
		Dept dept = new Dept();
		dept.setDeptName(deptName);
		dept.setDeptId(deptCode);
		dept.setContent(Tools.getDesc(imgMap.get("content")));
		dept.setImgs(Tools.getDesc(imgMap.get("imgs")));
		List<Map> imgs = JSONUtil.fromJson(dept.getImgs(), new TypeReference<List<Map>>(){});
		dept.setJson(jsonMap);
		if (imgs.size() != 0 ) {
			String url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
			dept.setJson("news_thumbnail", url);
		}
		dept.setJson("address",address);
		dept.setJson("phone",phone);
		dept.setBranch(branch);
		dept.setBranchName(branchName);
		dept.setHospital(hospital);
		dept.setImg(img);
		dept.setType(1);
		if("1".equals(dType)){
			dept.setParent("-1");
		} else {
			String parentId = input.getDesc("parentId","");
			dept.setParent(parentId);
		}
		DBTools.db("basedb").addItem(dept);
		return msg;
	}

	// 删除科室
	public Message deleteDept(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String deptCode = input.getDesc("deptCode","");
		QBuilder.db("basedb").execHQL("update Dept set status=" + STATUS_DISABLE + " where hospital=" + hospital + " and deptId='" + deptCode + "' and type=1");
		return msg;
	}

	// 修改科室
	public Message updateDept(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		//修改部门信息
		String deptCode = input.getDesc("deptCode", "").replace(".0","");
		String deptName = input.getDesc("deptName", "");
		String address = input.getDesc("address", "");
		String phone = input.getDesc("phone", "");
		String content = input.getDesc("content", "");
		Map<String, String> imgMap = getImg(content,PATTERN);
		Map jsonMap = new HashMap();
		jsonMap.put("attachs", new ArrayList());
		String img = input.getDesc("head_image","");
		List<Dept> list = QBuilder.db("basedb").queryHql("from Dept where hospital=" + hospital + " and deptId='" + deptCode + "' and status=" + STATUS_ENABLE + " and type=1");
		if(list.size() == 0)
			return new Message(30041, "没有该部门信息");
		Dept dept = list.get(0);
		dept.setDeptName(deptName);
		dept.setContent(Tools.getDesc(imgMap.get("content")));
		dept.setImgs(Tools.getDesc(imgMap.get("imgs")));
		List<Map> imgs = JSONUtil.fromJson(dept.getImgs(), new TypeReference<List<Map>>(){});
		dept.setJson(jsonMap);
		if (imgs.size() != 0 ) {
			String url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
			dept.setJson("news_thumbnail", url);
		}
		dept.setJson("address", address);
		dept.setJson("phone", phone);
		dept.setImg(img);
		DBTools.db("basedb").modItem(dept, dept.getId());
		return msg;
	}

	// 科室排序
	public Message sortDept(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String deptCodes = input.getDesc("deptCodes", "-1");
		List<String> list = stringToList(deptCodes);
		for (int i = 0; i < list.size();i++) {
			QBuilder.db("basedb").execHQL("update Dept set deptOrder=" + i + " where deptId='" + list.get(i) + "' and hospital=" + hospital + " and type=1");
		}
		return msg;
	}

	// 科室详情
	public Message showDept(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String deptCode = input.getDesc("deptCode","100601");
		List<Dept> deptList = QBuilder.db("basedb").queryHql("from Dept where hospital="+hospital+" and deptId='"+deptCode+"' and status="+STATUS_ENABLE + " and type=1");
		if(deptList.size() == 0)
			return new Message(30041, "没有该部门信息");
		msg.put("dept", deptList.get(0));
		return msg;
	}

	// 一级科室列表
	public Message firstDepts(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String branch = input.getDesc("branch", "1");
		List<Map> list = QBuilder.db("basedb").queryHql("select new Map(id as id,deptId as deptCode,deptName as deptName) from Dept where hospital=" + hospital + " and branch='" + branch + "' and status=" + STATUS_ENABLE + " and parent='-1'  and type=1  order by deptOrder asc");
		msg.put("depts", list);
		return msg;
	}

	// 根据一级科室id查询二级科室列表
	public Message secondDepts(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String deptCode = input.getDesc("deptCode","").replace(".0","");
		List<Map> deptList = QBuilder.db("basedb").queryHql("select new Map(id as id,deptId as deptCode,deptName as deptName) from Dept where hospital=" + hospital + " and parent='" + deptCode + "' and status=" + STATUS_ENABLE + " and type=1 order by deptOrder asc");
		msg.put("depts",deptList);
		return msg;
	}

	// 展示当前科室关联挂号科室
	public Message registerDepts(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String deptId = input.getDesc("deptId","");
		List<Map> linkList = QBuilder.db("basedb").queryHql("select new map(d.id as id,d.deptId as deptCode,d.deptName as deptName) from Dept d,dept_link dl where d.deptId=dl.other_id and dl.hospital=" + hospital + " and dl.dept_id='" + deptId + "' and dl.status=" + STATUS_ENABLE + " and dl.dept_type=6 and d.type=6 and d.hospital=" + hospital);
		msg.put("links", linkList);
		// 所有挂号科室
		List<Map> deptList = QBuilder.db("basedb").queryHql("select new map(id as id, deptId as dept_id, deptName as dept_name)from Dept where hospital=" + hospital + " and type=6 and status=" + STATUS_ENABLE);
		for (Map dept:deptList) {
			Integer id = (Integer)dept.get("id");
			dept.put("is_linked", 0);
			for (Map link:linkList) {
				Integer linkId = (Integer)link.get("id");
				if (linkId.equals(id))
					dept.put("is_linked", 1);
			}
		}
		msg.put("depts",deptList);
		return msg;
	}

	// 关联挂号科室
	public Message deptLink(Input input) {
		Message msg = new Message();
		//管理挂号科室，dept_id存放主键，other_id存放非主键
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String deptId = input.getDesc("dept_id","111").replace(".0","");
		String other_str = input.getDesc("other_str");
		List other = JSONUtil.fromJson(other_str, new TypeReference<List>(){});
		List<Map> add_result = new ArrayList<Map>();
		List<Map> mod_result = new ArrayList<Map>();
		//先将所有的关联科室status置为0
		QBuilder.db("basedb").execHQL("update dept_link set status=0 where hospital = " + hospital + " and dept_id='"+deptId+"' and dept_type=6");
		for(Object otherId:other){
			Map map = new HashMap();
			map.put("dept_id", deptId);
			map.put("other_id", otherId + "");
			map.put("dept_type", "6");
			map.put("status", STATUS_ENABLE);
			map.put("hospital", hospital);
			map.put("create_time", System.currentTimeMillis());
			map.put("json","{}");
			add_result.add(map);
		}
		if (add_result.size() != 0)
			DBTools.db("basedb").addItem("dept_link", add_result);
		return msg;
	}

	// 添加医生
	public Message addDoctor(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String secondId = input.getDesc("second_id", "-1").replace(".0","");
		String expertId = input.getDesc("doctorCode","");
		String name = input.getDesc("name","");
		String sex = input.getDesc("sex","");
		String level = input.getDesc("level","");
		String avatar = input.getDesc("head_image","");
		String specialty = input.getDesc("specialty","");
		String content = input.getDesc("content","");
		String isExpert = input.getDesc("isExpert","");//1是专家 0是普通
		String time = "";
		if("1".equals(isExpert))
			time = input.getDesc("time", "");
		List<Expert> list = QBuilder.db("basedb").queryHql("from Expert where hospital=" + hospital + " and expertId='" + expertId + "' and deptId=" + secondId);
		if(list.size()>0)
			return new Message(30031, "");
		Expert expert = new Expert();
		expert.setName(name);
		expert.setTitle(level);
		expert.setAvatar(avatar);
		if("1".equals(isExpert))
			expert.setTime(time);
		expert.setJson("sex",sex);
		expert.setJson("isExpert", isExpert);
		expert.setHospital(hospital);
		expert.setDeptId(Integer.valueOf(secondId));
		expert.setExpertId(expertId);
		expert.setSpecialty(specialty);
		expert.setContent(content);
		DBTools.db("basedb").addItem(expert);
		return msg;
	}

	// 删除医生
	public Message deleteDoctor(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		//删除医生
		String expertId = input.getDesc("doctorCode","").replace(".0","");
		QBuilder.db("basedb").execHQL("update Expert set status=" + STATUS_DISABLE + " where hospital=" + hospital + " and expertId='" + expertId + "'");
		return msg;
	}

	// 修改医生
	public Message updateDoctor(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		Integer id = input.getInt("id", -1);
		String name = input.getDesc("name","");
		String sex = input.getDesc("sex","");
		String level = input.getDesc("level","");
		String avatar = input.getDesc("head_image","");
		String specialty = input.getDesc("specialty","");
		String content = input.getDesc("content","");
		String isExpert = input.getDesc("isExpert","");//1是专家 0是普通
		String time = "";
		if("1".equals(isExpert))
			time = input.getDesc("time", "");
		List<Expert> list = QBuilder.db("basedb").queryHql("from Expert where hospital=" + hospital + " and id=" + id);
		if(list.size() == 0)
			return new Message(30041, "没有这个医生");
		Expert expert = list.get(0);
		expert.setName(name);
		expert.setTitle(level);
		expert.setAvatar(avatar);
		if("1".equals(isExpert))
			expert.setTime(time);
		expert.setJson("sex",sex);
		expert.setJson("isExpert", isExpert);
		expert.setSpecialty(specialty);
		expert.setContent(content);
		DBTools.db("basedb").modItem(expert, id);
		return msg;
	}

	// 医生列表
	public Message doctors(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String first_id = input.getDesc("first_id","-1").replace(".0","");
		String second_id = input.getDesc("second_id","-1").replace(".0","");
		String keywords = input.getDesc("keywords", "");
		String str = "";
		Integer pageNum = input.getInt("page", 1);; // 页码
		Integer itemCount = input.getInt("item_count", 7); // 每一页条目
		if("-1".equals(second_id)){
			if ("-1".equals(first_id)) {
				str = "1=1";
			} else {
				List<Integer> idList = QBuilder.db("basedb").queryHql("select id from Dept where hospital=" + hospital + " and parent=(select deptId from Dept where hospital=" + hospital + " and id=" + first_id + " and status=" + STATUS_ENABLE + ") and status=" + STATUS_ENABLE);
				if(idList == null || idList.size() == 0 ){
					idList = QBuilder.db("basedb").queryHql("select id from Dept where hospital=" + hospital + " and id=" + first_id + "  and status=" + STATUS_ENABLE);
				}
				str = "e.deptId in ( 0  ";
				for(Integer id:idList){
					str += ","+id;
				}
				str += ")";
				str = str.replace("(,","(");
			}
		} else {
			str = "e.deptId="+second_id;
		}
		Where where = new Where("e.hospital=",hospital).and("d.id=e.deptId").and("e.status=",STATUS_ENABLE).and(str);
		if (!"".equals(keywords)) {
			where.and("e.name like '%" + keywords + "%' or e.expertId like '%" + keywords + "%'");
		}
		List<Map> ranks = QBuilder.db("basedb").select("new Map(e.id as id,e.expertId as expertId,e.avatar as head_image,e.name as name,e.title as level,d.deptName as deptName)").from("Expert e,Dept d").where(where).page(itemCount, pageNum).query().getResultObj();
		List<Long> rankCount = QBuilder.db("basedb").select("count(*)").from("Expert e,Dept d").where(where).query().getResultObj();
		Long size = rankCount.get(0);
		Map resultMap = new HashMap();
		resultMap.put("rank", ranks);
		resultMap.put("current_page", pageNum);
		resultMap.put("page_count",  size%itemCount == 0?(size/itemCount):(size/itemCount + 1));
		resultMap.put("count",  size);
		msg.put("data", resultMap);
		return msg;
	}

	// 展示单条医生详情，用于查看和编辑
	public Message showDoctor(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String expertId = input.getDesc("id", "43146").replace(".0","");
		List<Map> list = QBuilder.db("basedb").select("new Map(e.id as id,e.name as name ,e.title as title,e.expertId as expertId,d.deptName as deptName,e.specialty as specialty,e.content as content,e.jsonString as jsonString,e.time as time,e.avatar as head_image)").from("Expert e,Dept d").where(new Where("e.hospital=",hospital).and("e.id=", expertId).and("e.status=", STATUS_ENABLE).and("e.deptId=d.id")).query().getResultObj();
		if (list.size() > 0) {
			Map expert = list.get(0);
			Map jsonMap = JSONUtil.fromJson(Tools.getDesc(expert.get("jsonString"), "{}"), new TypeReference<Map>(){});
			expert.put("sex", Tools.getDesc(jsonMap.get("sex"), "1"));
			expert.put("isExpert", Tools.getDesc(jsonMap.get("isExpert"), "1"));
			msg.put("expert", expert);
		}
		else
			msg.setErrcodeAndErrmsg(30041, "没有该医生信息");
		return msg;
	}

	// 展示医院详情
	public Message showHospital(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		List<Map> messageList = QBuilder.db("basedb").queryHql("from hospital_intro where hospital = " + hospital + " and type = 1");
		if (isEmpty(messageList))
			return new Message(30041, "没有医院信息");
		msg.put("data", messageList.get(0));
		return msg;
	}

	// 展示医院详情
	public Message updateHospital(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		String name = input.getDesc("name", "");
		String level = input.getDesc("level", "");
		String phone = input.getDesc("phone", "");
		String address = input.getDesc("address", "");
		String url = input.getDesc("url", "");
		String introduction = input.getDesc("introduction", "");
		Map<String, String> imgMap = getImg(introduction,  PATTERN);
		String head_image = input.getDesc("head_image","");
		List<Map> checkList = QBuilder.db("basedb").queryHql("from hospital_intro where hospital="+hospital + " and type = 1");
		try{
			if(checkList.size()==1){
				//更新医院信息
				Map editMap = checkList.get(0);
				editMap.put("name", name);
				editMap.put("level", level);
				editMap.put("phone", phone);
				editMap.put("address", address);
				editMap.put("url", url);
				editMap.put("introduction", Tools.getDesc(imgMap.get("content")));
				editMap.put("imgs", Tools.getDesc(imgMap.get("imgs")));
				editMap.put("head_image", head_image);
				List<Map> imgs = JSONUtil.fromJson(editMap.get("imgs")+"", new TypeReference<List<Map>>(){});
				if (imgs.size() != 0 ) {
					String img_url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
					editMap.put("json","{\"news_thumbnail\":\""+img_url+"\"}");
				}
				DBTools.db("basedb").modItem("hospital_intro", editMap);
				msg.put("check", "update");
			} else {
				//新建医院信息
				Map addMap = new HashMap();
				addMap.put("name", name);
				addMap.put("level", level);
				addMap.put("phone", phone);
				addMap.put("address", address);
				addMap.put("url", url);
				addMap.put("introduction", Tools.getDesc(imgMap.get("content")));
				addMap.put("imgs", Tools.getDesc(imgMap.get("imgs")));
				addMap.put("head_image", head_image);
				addMap.put("hospital", hospital+"");
				addMap.put("create_time", System.currentTimeMillis()+"");
				addMap.put("type", "1");
				List<Map> imgs = JSONUtil.fromJson(addMap.get("imgs")+"", new TypeReference<List<Map>>(){});
				if (imgs.size() != 0 ) {
					String img_url = ImageUtil.small(Tools.getDesc(imgs.get(0).get("src")));
					addMap.put("json","{\"news_thumbnail\":\""+img_url+"\"}");
				} else {
					addMap.put("json","{}");
				}
				DBTools.db("basedb").addItem("hospital_intro",addMap);
				msg.put("check", "add");
			}
		} catch (Exception e){
			e.printStackTrace() ;
		}
		return msg;
	}
	// 展示意见反馈
	public Message showFeedback(Input input) {
		Message msg = new Message();
		Integer hospital = input.getInt("hospital", -1);    // 医院编号
		List<Map> feedbackList = QBuilder.db("basedb").queryHql("from Feedback where hospital = " + hospital + " order by id");
		if (isEmpty(feedbackList))
			return new Message(30041, "没有反馈信息");
		msg.put("data", feedbackList);
		return msg;
	}
%>
